import { BaseService } from '@src/service/base/base.service';
import { Injectable, HttpException, HttpStatus, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, getManager, EntityManager } from 'typeorm';
import { DictValueEntity } from '@src/entities/sys/dict_value.entity';
import { AssiginDataDto } from '@src/controllers/admin/system/dict/dto';
import { async } from 'rxjs';

@Injectable()
export class DictValueService extends BaseService {
  constructor(
    @InjectRepository(DictValueEntity)
    private readonly dictValueRepository: Repository<DictValueEntity>,
  ) {
    super(dictValueRepository)
  }

  /**
   * @Description: 给字典添加数据
   * @param {type}
   * @return:
   */
  public async assignData(data: AssiginDataDto): Promise<any> {
    const { dictId, dictList } = data;
    /**
    * 1.先将表中dictId的删除
    * 2.重新插入数据
    */
    return getManager()
      .transaction(async (entityManager: EntityManager) => {
        await entityManager.delete(DictValueEntity, { dictId: Number(dictId) });
        for (const item of dictList) {
          await entityManager.save(DictValueEntity, { dictId: Number(dictId), key: item['key'], value: item['value'] })
        }
      }).then(async () => {
        Logger.log('字典数据创建成功');
        return true;
      }).catch((e) => {
        Logger.error('字典数据创建错误', e);
        throw new HttpException('字典数据创建错误', HttpStatus.BAD_REQUEST);
      });
  }
}